package com.zbf.tspring.service;

import com.zbf.tspring.dao.TestDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: LCG
 * 作者: LCG
 * 日期: 2021/3/22  9:10
 * 描述: 测试事务的嵌套行为
 *
 * 同一类类中的事务嵌套
 *
 */

@Component
public class TestService2 {

    @Autowired
    private TestDao testDao;

    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    @Async("threadPoolExecutor")
    public void test01(int status){
        Map<String,Object> map=new HashMap<>();
        map.put("id",3);
        map.put("quantity",300);
        //更新订单
        testDao.updateOrder(map);
        if(status==1){
            throw new RuntimeException("=====================");
        }
    }


    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void  test02( Map<String,Object> map){
        //更新库存
        testDao.updateStock(map);

        test01(1);
    }





    /**
     * 作者: LCG
     * 日期: 2021/3/22  9:20
     * 描述: 一个没有事务的方法 调用一个有事务的方法
     * @Param []
     * @Return void
     */
    public void test03(int status){

        Map<String,Object> map=new HashMap<>();
        map.put("id",3);
        map.put("quantity",300);

        testDao.updateOrder(map);
        //有事务
        test04(map);

        if(status==1){

            throw new RuntimeException("=====================");

        }


    }

    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void test04(Map<String,Object> map){

        testDao.updateStock(map);
 
    }





    /**
     * 作者: LCG
     * 日期: 2021/3/22  9:31
     * 描述: 测试 两个或者多个方法  都有事务的嵌套情况
     * @Param []
     * @Return void
     */
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void test05(){

        Map<String,Object> map=new HashMap<>();
        map.put("id",3);
        map.put("quantity",300);

        testDao.updateOrder(map);

        test06(map);

    }


    @Transactional(propagation = Propagation.NOT_SUPPORTED,rollbackFor = Exception.class)
    public void test06( Map<String,Object> map){

        int i = testDao.updateStock(map);

        if(i == 1){
            throw new RuntimeException("============测试都有事务的嵌套=========");
        }

    }


}
